import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../generated/assets.dart';

//滚动顶部吸顶
class ScrollTopStickyPage extends StatefulWidget {
  const ScrollTopStickyPage({super.key});

  @override
  State<ScrollTopStickyPage> createState() => _ScrollTopStickyPageState();
}

class _ScrollTopStickyPageState extends State<ScrollTopStickyPage> {
  final ScrollController _scrollController = ScrollController();
  double _appBarAlpha = 0.0;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      final double offset = _scrollController.offset;
      _appBarAlpha = (offset / 300).clamp(0.0, 1.0);
      print("ddddddddd${_appBarAlpha}");
      setState(() {});
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildCorrectLayout(), // 修复布局结构
    );
  }

  Widget _buildCorrectLayout() {
    final statusBarHeight = MediaQuery.of(context).padding.top;
    return Stack(
      children: [
        Positioned.fill(
            child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverToBoxAdapter(
              child: SizedBox(
                height: 500,
                child: Image.asset(Assets.imgTopImg, fit: BoxFit.cover),
              ),
            ),
            // 添加固定标题
            // _buildStickyHeader("固定标题"),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) => ListTile(title: Text('Item $index')),
                childCount: 100,
              ),
            ),
          ],
        )),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Container(
            padding: EdgeInsets.only(top: statusBarHeight),
            color: Colors.white.withValues(alpha: _appBarAlpha),
            height: kToolbarHeight + statusBarHeight,
            child: Stack(
              children: [
                Positioned(
                    right: 0,
                    child: Row(
                      children: _buildActionIcons(),
                    ))
              ],
            ),
          ),
        ),
      ],
    );
  }

// 创建固定标题
  Widget _buildStickyHeader(String text) {
    return SliverPersistentHeader(
      pinned: true,
      delegate: _StickyHeaderDelegate(
        minHeight: 40.0,
        maxHeight: 40.0,
        child: Container(
          color: Colors.blue[800],
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 16),
          child: Text(
            text,
            style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  Widget _buildLeadingIcon() {
    return IconButton(
      icon: Icon(
        Icons.menu,
        color: _appBarAlpha > 0.5 ? Colors.black : Colors.white,
      ),
      onPressed: () {},
    );
  }

  List<Widget> _buildActionIcons() {
    return [
      IconButton(
        icon: Icon(Icons.search, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
      IconButton(
        icon: Icon(Icons.share, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
      IconButton(
        icon: Icon(Icons.more_vert, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
    ];
  }

  Widget _buildTitle() {
    return Text(
      'Collapsing Toolbar',
      style: TextStyle(
        color: _appBarAlpha > 0.5 ? Colors.black : Colors.white,
        fontSize: 18,
      ),
    );
  }

  Widget _buildScrollContent() {
    return ListView.builder(
      padding: EdgeInsets.only(top: 0 // 留出顶部间距
          ),
      itemCount: 10,
      itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
    );
  }
// Widget _buildScrollContent() {
//   return Builder(
//     builder: (context) {
//       // 关键修复2：动态计算可用高度
//       final mediaQuery = MediaQuery.of(context);
//       return SizedBox(
//         // 减去状态栏和导航栏高度
//         height: mediaQuery.size.height - mediaQuery.padding.top - kToolbarHeight,
//         child: ListView.builder(
//           padding: EdgeInsets.only(
//               top: 8, // 留出顶部间距
//               bottom: mediaQuery.padding.bottom // 避免底部被遮挡
//           ),
//           itemCount: 10,
//           itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
//         ),
//       );
//     },
//   );
// }
}

// 自定义Delegate实现
class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double minHeight;
  final double maxHeight;
  final Widget child;

  _StickyHeaderDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  @override
  Widget build(_, double shrinkOffset, bool overlapsContent) {
    return SizedBox.expand(child: child);
  }

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => maxHeight;

  @override
  bool shouldRebuild(covariant _StickyHeaderDelegate oldDelegate) {
    return oldDelegate.minHeight != minHeight || oldDelegate.maxHeight != maxHeight || oldDelegate.child != child;
  }
}
